package com.example.commom.utils;

import com.example.commom.dsl.ChapterDSL;
import com.example.feign.result.AjaxResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86187
 * Date: 2023-10-21
 * Time: 21:46
 */
@Component
public class ESUtils {

    @Autowired
    private ObjectMapper objectMapper;

    public AjaxResult handleSuggestionResponse( SearchResponse response, String name) {

        Suggest suggest = response.getSuggest();

        CompletionSuggestion suggestions = suggest.getSuggestion(name);

        List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();

        List<String> result = new ArrayList<>();
        for (CompletionSuggestion.Entry.Option option : options) {
            String text = option.getText().toString();
            result.add(text);
        }
        return AjaxResult.success(result);
    }

    public AjaxResult handleSuggestionChapterResponse( SearchResponse response, String name, Long bookId) {
        try {
            Suggest suggest = response.getSuggest();

            CompletionSuggestion suggestions = suggest.getSuggestion(name);

            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();

            List<String> result = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {

                String string = option.getHit().getSourceAsString();

                ChapterDSL chapterDSL = objectMapper.readValue(string, ChapterDSL.class);

                if (Objects.equals(chapterDSL.getBookId(), bookId)) {
                    String text = option.getText().toString();
                    result.add(text);
                }
            }

            return AjaxResult.success(result);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
